/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2020年11月2日
 */
package com.massyframework.beanskin.service;

import java.util.Objects;

import com.massyframework.beanskin.assembly.Assembly;
import com.massyframework.beanskin.assembly.AssemblyContext;
import com.massyframework.beanskin.assembly.AssemblyContextSupport;

/**
 * 支持服务跟踪的组件
 * 
 * <p>
 * 抽象类，能跟踪注册到ServiceRepository中的服务。
 * @author huangkh
 *
 */
public abstract class ServiceTrackerSupport<T> extends AssemblyContextSupport implements ServiceTrackerCustomizer<T> {

	private Class<T> serviceType;
	private ServiceTracker<T> tracker;
	
	/**
	 * 
	 */
	public ServiceTrackerSupport(Class<T> serviceType) {
		this.serviceType = Objects.requireNonNull(serviceType, "\"serviceType\" cannot be null.");
	}

	@Override
	protected synchronized void bindAssemblyContext(AssemblyContext context) {
		super.bindAssemblyContext(context);
		if (this.tracker == null) {
			Assembly assembly = context.getAssociatedAssembly();
			this.tracker = new ServiceTracker<T>(assembly, 
					this.getServiceType(), this.getFilterString(), this);
			this.tracker.open();
		}
	}

	@Override
	protected synchronized void unbindAssemblyContext(AssemblyContext context) {
		if (this.tracker != null) {
			this.tracker.close();
			this.tracker = null;
		}
		super.unbindAssemblyContext(context);
	}

	/**
	 * 跟踪的服务类型
	 * @return {@link Class}
	 */
	protected Class<T> getServiceType(){
		return this.serviceType;
	}
	
	/**
	 * 过滤服务的字符串，默认返回null.
	 * @return {@link String}
	 */
	protected String getFilterString() {
		return null;
	}
}
